# -*- coding: UTF-8 -*- #
"""
@filename:03-1滑块.py
@author:JiYujia
@time:2022-09-05
"""
# 实现滑块调色板功能
import cv2
import numpy as np

def nothing(x):
    pass

# 创建一个图片
img = np.zeros((500, 500, 3), np.uint8)

# 创建一个窗口来放置调色板——给窗口起名image
cv2.namedWindow('image')
# 调整窗口大小
cv2.resizeWindow('image', 500, 500)

# 放置滑动条，3个rgb+一个开关共四个
cv2.createTrackbar('R', 'image', 0, 255, nothing)
cv2.createTrackbar('G', 'image', 0, 255, nothing)
cv2.createTrackbar('B', 'image', 0, 255, nothing)
# 开关
switch = '0:0FF\n1:OF'
cv2.createTrackbar(switch, 'image', 0, 1, nothing)

# 循环显示调色板——改变调色板的颜色
while True:
    r = cv2.getTrackbarPos('R', 'image')
    g = cv2.getTrackbarPos('G', 'image')
    b = cv2.getTrackbarPos('B', 'image')
    s = cv2.getTrackbarPos(switch, 'image')

    if s == 0:
        # 如果开关是关的，显示黑色
        img[:] = 0
    else:
        # 在opencv中，rgb颜色空间的顺序是bgr
        img[:] = [b, g, r]

    cv2.imshow('image', img)
    k = cv2.waitKey(1) & 0xFF
    # sc的ASCII码为27，即判断是否按下esc键
    # 引用&0xff，正是为了只取按键对应的ASCII值后8位来排除不同按键的干扰进行判断按键是什么
    if k == 27:
        break
    if cv2.getWindowProperty('image', cv2.WND_PROP_VISIBLE) < 1:
        break

cv2.destroyAllWindows()
